
#include "InvoiceItemModel.h"
#include "Customer.h"
#include "Helper.h"

#include <QBrush>
#include <QFile>
#include <assert.h>
#include <QDebug>

using namespace ecocity;

const int InvoiceItemsModel::s_columns = 13;

InvoiceItemsModel::InvoiceItemsModel( const std::vector< InvoiceItem >& invoice_items,
                              QObject *parent )
    : QStandardItemModel( parent ),
      m_items( invoice_items )
{
    reset( invoice_items );
}

//---------------------------------------------------------------

void
InvoiceItemsModel::reset( const std::vector< InvoiceItem >& invoice_items )
{
    // Do not call clear cause columns resize again
    removeRows( 0, rowCount() );

    for ( size_t row = 0; row < invoice_items.size( ); ++row )
    {
        add_new_invoice_item( invoice_items[ row ] );
    }

    m_items = invoice_items;

    emit model_changed( );
}

//---------------------------------------------------------------

QVariant
InvoiceItemsModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
    if ( role != Qt::DisplayRole || orientation != Qt::Horizontal )
    {
        return QVariant();
    }

    switch( section )
    {
    case ITEM_QUANTITY: return QString( "Cantidad" );

    case ITEM_WEIGHT: return QString( "Peso" );

    case ITEM_PRICE_TYPE: return QString( "Tipo Precio" );

    case ITEM_PRODUCT_NAME: return QString( "Producto" );

    case ITEM_UNTAXED_PRICE_UNIT_OR_KILO: return QString( "Por Un./kg" );

    case ITEM_UNTAXED_PRICE_WITHOUT_DISCOUNT: return QString( "Precio (sin IVA)" );

    case ITEM_DISCOUNT_RATE: return QString::fromUtf8( "Descuento %" );

    case ITEM_DISCOUNT_EUR: return QString( "Descuento EUR" );

    case ITEM_TOTAL_UNTAXED_PRICE: return QString( "Total(sin IVA)" );

    case ITEM_TAX_RATE: return QString::fromUtf8( "IVA %" );

    case ITEM_TAXES: return QString( "IVA EUR" );

    case ITEM_TOTAL_PRICE: return QString( "Precio Total" );

    case ITEM_UNIQUE_ID: return QString( "Id" );

    default:
        return QVariant();
    }
}

//---------------------------------------------------------------

Qt::ItemFlags
InvoiceItemsModel::flags ( const QModelIndex & /*index*/ ) const
{
    // Not editable ( Qt::ItemIsEditable
    return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}

//---------------------------------------------------------------

bool
InvoiceItemsModel::add_new_invoice_item( const ecocity::InvoiceItem& invoice_item )
{
    qDebug() << "\nInvoiceItemModel add new invoice item\n" << endl;

    QList<QStandardItem*> items;

    QStandardItem* quantity = new QStandardItem;
    QStandardItem* weight = new QStandardItem;
    QStandardItem* untaxed_price_unit_or_kg = new QStandardItem;
    QStandardItem* untaxed_price_without_discount = new QStandardItem;
    QStandardItem* untaxed_price_with_discount = new QStandardItem;
    QStandardItem* discount_rate = new QStandardItem;
    QStandardItem* discount = new QStandardItem;
    QStandardItem* tax_rate = new QStandardItem;
    QStandardItem* taxes = new QStandardItem;
    QStandardItem* total_price = new QStandardItem;
    QStandardItem* id = new QStandardItem;

    quantity->setData( invoice_item.quantity(), Qt::EditRole );
    discount_rate->setData( QString::number( invoice_item.discount_rate( ), 'f', 2 ), Qt::EditRole );
    tax_rate->setData( invoice_item.product().tax_rate( ), Qt::EditRole );
    id->setData( invoice_item.id(), Qt::EditRole );

    weight->setData( QString::number( invoice_item.weight( ), 'f', 3 ) , Qt::EditRole );

    // needed to display price/kg or Uni (without considering weight or quantity)
    untaxed_price_unit_or_kg->setData(
                QString::number( invoice_item.product().untaxed_price( invoice_item.customer_type() ), 'f', 2 ),
                Qt::EditRole );

    untaxed_price_without_discount->setData(
                QString::number( invoice_item.untaxed_cost_without_discount(), 'f', 2 ),
                Qt::EditRole );

    untaxed_price_with_discount->setData(
                QString::number( invoice_item.untaxed_cost_with_discount(), 'f', 2 ),
                Qt::EditRole );

    discount->setData(
                QString::number( invoice_item.total_discount(), 'f', 2 ),
                Qt::EditRole );

    taxes->setData(
                QString::number( invoice_item.taxes_cost( ), 'f',2 ),
                Qt::EditRole );

    total_price->setData( QString::number( invoice_item.total_cost( ), 'f', 2 ),
                               Qt::EditRole );


    items << quantity                                                                   //    ITEM_QUANTITY                           = 0,
          << weight                                                                     //    ITEM_WEIGHT                             = 1,
          << new QStandardItem( invoice_item.product().name() )                         //    ITEM_PRODUCT_NAME                       = 2,
          << untaxed_price_unit_or_kg  // needed to display price/kg or Uni             //    ITEM_UNTAXED_PRICE_UNIT_OR_KILO         = 3,
          << untaxed_price_without_discount                                             //    ITEM_UNTAXED_PRICE_WITHOUT_DISCOUNT     = 4,
          << discount_rate                                                              //    ITEM_DISCOUNT_RATE                      = 5,
          << discount                                                                   //    ITEM_DISCOUNT_EUR                       = 6,
          << untaxed_price_with_discount                                                //    ITEM_TOTAL_UNTAXED_PRICE                = 7,
          << tax_rate                                                                   //    ITEM_TAX_RATE                           = 8,
          << taxes                                                                      //    ITEM_TAXES                              = 9,
          << total_price                                                                //    ITEM_TOTAL_PRICE                        = 10,
          << new QStandardItem( Product::to_string( invoice_item.price_type( ) ) )      //    ITEM_PRICE_TYPE                         = 11
          << id;                                                                        //    ITEM_UNIQUE_ID                          = 12

    if ( items.size( ) != s_columns )
    {
        // Ensure you don't forget anything
        assert( 0 );
        return false;
    }

    insertRow( rowCount( ), items );

    m_items.push_back( invoice_item );

    return true;
}

//---------------------------------------------------------------

const InvoiceItem*
InvoiceItemsModel::invoice_item( const QModelIndex &index ) const
{
    int quantity = data( this->index( index.row( ), ITEM_QUANTITY ) ).toInt( );
    float weight = data( this->index( index.row( ), ITEM_WEIGHT ) ).toFloat( );
    float discount_rate = data( this->index( index.row( ), ITEM_DISCOUNT_RATE ) ).toFloat( );
    QString name = data( this->index( index.row( ), ITEM_PRODUCT_NAME ) ).toString();

    for ( size_t i = 0; i < m_items.size(); ++i )
    {
        const InvoiceItem& item = m_items[ i ];

        if ( item.quantity() == quantity
             && item.weight() == weight
             && item.product().name() == name
             && item.discount_rate() == discount_rate )
        {
            return &item;
        }
    }

    return 0;
}

//---------------------------------------------------------------

void
InvoiceItemsModel::save( const QString & /*file_name*/ ) const
{
      // TODO
//    if( file_name.isEmpty( ) )
//    {
//        return;
//    }

//    QFile file( file_name );

//    if ( !file.open( QIODevice::WriteOnly ) )
//    {
//        return;
//    }

//    QTextStream out( &file );

//    for ( int row = 0; row < rowCount(); ++row )
//    {
//        for ( int column = 0; column < s_columns; ++column )
//        {
//            switch (column) {
//            case INVOICE_ID:
//                out << item( row, column )->data( Qt::EditRole ).toInt();
//                break;
//            case INVOICE_TOTAL_TAXES:
//            case INVOICE_TOTAL_WITHOUT_TAX:
//            case INVOICE_TOTAL_PROFIT:
//            case INVOICE_TOTAL_PRICE:
//                out << item( row, column )->data( Qt::EditRole ).toFloat();
//                break;
//            case INVOICE_CUSTOMER_NAME:
//            case INVOICE_DATE:
//            case INVOICE_PRODUCT_NAMES:
//                out << item( row, column )->text();
//                break;
//            default:
//                break;
//            }

//            if ( column < s_columns - 1 )
//            {
//                out << ",";
//            }
//        }

//        out << "\n";
//    }

//    file.close();
}

//---------------------------------------------------------------


